import { parseTime } from './ruoyi'
// import {formatDate,getInterValDays} from '@/utils'

/**
 * 表格时间格式化
 */
export function formatDate (cellValue,type=1) {
  if (cellValue == null || cellValue == "") return "";
  var date = new Date(cellValue)
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()

  if (type == 1) {
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
  } else if (type == 2) {
    return year + '-' + month + '-' + day 
  } else if (type == 3) {
    return year 
  } else if (type == 4) {
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes
  } else if (type == 5) {
    return year + '-' + month + '-' + day + ' ' + hours 
  } else {
    return year + month + day
  }
}

/**
 * 获取time与当前时间 间隔天数
 */
export function getInterValDays (time, time2) {
  if (time == null || time == "") return ""; 
  let times = 0
  if (time2) {
    times = new Date(time2).getTime() - new Date(time).getTime()
  } else {
    times = new Date().getTime() - new Date(time).getTime()
  }
  let days = parseInt(times / (24 * 3600 * 1000))

  return days +1
}

/**
 * 获取给定日期 time 与当前时间之间的间隔天数
 * @param {string|Date} time - 给定的日期，可以是日期字符串或 Date 对象
 * @returns {number} 间隔天数
 */
export function getDaysDifference (time) {
  // 将给定的时间转换为 Date 对象
  const givenTime = new Date(time);

  // 获取当前时间
  const currentTime = new Date();

  // 计算两个日期之间的毫秒差
  const differenceInMilliseconds = Math.abs(currentTime - givenTime);

  // 将毫秒差转换为天数
  const differenceInDays = differenceInMilliseconds / (1000 * 60 * 60 * 24);

  // 返回间隔天数
  return Math.floor(differenceInDays);
}


// 时区时间转化
export function areaTimeTransform (targetTime) {
  // 目标时区，东8区
  let targetTimezone = -8
  let time = formatDate(targetTime)
  // console.log(time)
  // 当前时区与中时区时差，以min为维度
  let _dif = new Date().getTimezoneOffset()
  // 本地时区时间 + 时差  = 中时区时间
  // 目标时区时间 + 时差 = 中时区时间
  // 目标时区时间 = 本地时区时间 + 本地时区时差 - 目标时区时差
  // 东8区时间
  let east9time = new Date(time).getTime() + _dif * 60 * 1000 - (targetTimezone * 60 * 60 * 1000)
  return new Date(east9time)
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime (time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject (url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength (str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray (actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param (json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj (url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text (val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge (target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass (element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime (type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone (source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr (arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString () {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass (ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass (ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass (ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function makeMap (str, expectsLowerCase) {
  const map = Object.create(null)
  const list = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val]
}

// 格式化箱型  <!-- 箱型：5 - 40HQ  10 - 40GP  15 - 20HQ   20 - 20GP -->
export function formatBoxType (str) {
  if(typeof str !== 'number' ) str = Number(str)
  switch(str){
    case 5:
      return '40HQ'
      break;
    case 10:
      return '40GP'
      break;
    case 15:
      return '20HQ'
      break;
    case 20:
      return '20GP'
      break;
  }
}
// 格式化箱况 <!-- boxCondition 5-全新   10-次新  15-适货 20-混提(次新或者适货) -->
export function formatBoxCondition (str) {
  if(typeof str !== 'number' ) str = Number(str)
  switch(str){
    case 5:
      return '全新'
      break;
    case 10:
      return '次新'
      break;
    case 15:
      return '适货'
      break;
    case 20:
      return '混提'
      break;
  }
}

export function warTime (timeStr) {
  // if(timeStr.length ){

  // }
  const now1 = new Date();
  // const formattedDate1 = now1.toISOString(); 

  const formattedDate1 = `${now1.getFullYear()}${String(now1.getMonth() + 1).padStart(2, '0')}${String(now1.getDate()).padStart(2, '0')}`;
  console.log("formattedDate1",formattedDate1);

  const now2 = new Date(timeStr);
  const formattedDate2 = `${now2.getFullYear()}${String(now2.getMonth() + 1).padStart(2, '0')}${String(now2.getDate()).padStart(2, '0')}`;
  console.log("formattedDate2",formattedDate2);
 
}
//值域金额
export function formatterNumber(value){ 
  const val = value.replace(/[^\d.]/g, '').replace(/(\.\d*)\./g, '$1').replace(/^(\d{5})\d+/, '$1').replace(/\.(\d{2})\d+/, '.$1')
  if (val.indexOf('.') === -1) {
    return (val- 0)
  }else {
    const valArr = val.split('.')
    return (valArr[0] - 0).toString() + '.' + valArr[1]
  }
}
//值域金额可以为空
export function formatterNumberKo(value){ 
  const val = value.replace(/[^\d.]/g, '').replace(/(\.\d*)\./g, '$1').replace(/^(\d{5})\d+/, '$1').replace(/\.(\d{2})\d+/, '.$1')
  if (val.indexOf('.') === -1) {
    if(val){
      return (val- 0)
    }else{
      return val
    }
  }else {
    const valArr = val.split('.')
    return (valArr[0] - 0).toString() + '.' + valArr[1]
  }
}
//值域汇率
export function formatterNumberFee(value){ 
  const val = value.replace(/[^\d.]/g, '').replace(/(\.\d*)\./g, '$1').replace(/^(\d{2})\d+/, '$1').replace(/\.(\d{2})\d+/, '.$1')
  if (val.indexOf('.') === -1) {
    return (val- 0)
  }else {
    const valArr = val.split('.')
    return (valArr[0] - 0).toString() + '.' + valArr[1]
  }
}
export function inputText(value){
  return value.replace(/[^a-zA-Z\u4e00-\u9fa5]/g, '')
}
//值域表情
export function containsEmoji  (value) {
  return value.replace(/(\u0000-\u001F)|(\u2000-\u206F)|(\u2190-\u23FF)|(\u2400-\u277F)|(\u2800-\u28FF)|(\u2E80-\u2EFF)|(\u2F00-\u2FDF)|(\u2FF0-\u2FFF)|(\u3000-\u303F)|(\u3040-\u309F)|(\u30A0-\u30FF)|(\u3100-\u312F)|(\u3130-\u318F)|(\u3190-\u319F)|(\u31A0-\u31BF)|(\u31F0-\u31FF)|(\u3200-\u32FF)|(\u3300-\u33FF)|(\uFE10-\uFE1F)|(\uFE30-\uFE4F)|(\uFE50-\uFE6F)|(\uFF00-\uFFFF)|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\n\r]/, '')
}

export const exportDefault = 'export default '